﻿using System.Collections.Generic;
using System.Linq;
using TechnicalIndicators.Points;
using Utils;

namespace TechnicalIndicators.DateBased
{
	public class MovingAverage : GeneratorBase<DatedSeriePoint, DatedSeriePoint>
	{
		#region Attributes

		private int _valuesProcessed;
		private int _period;
		private readonly List<decimal> _values;

		#endregion

		#region Public Methods
		
		public MovingAverage()
		{
			_values = new List<decimal>();
		}

		public MovingAverage(ObservableCollection2<DatedSeriePoint> destination) : base(destination)
		{
			_values = new List<decimal>();
		}

		public void Configure(int samples)
		{
			_period = samples;
		}

		protected override DatedSeriePoint CreatePoint(DatedSeriePoint point)
		{
			DatedSeriePoint newPoint = null;

			_valuesProcessed++;
			_values.Add(point.Y);

			if (_valuesProcessed > _period)
			{
				decimal firstValue = _values[0];
				decimal currentValue = point.Y;
				_values.RemoveAt(0);

				newPoint = new DatedSeriePoint(point.X, base.LastValue.Y + ((currentValue - firstValue) / _period));
			}
			else if (_valuesProcessed == _period)
			{
				decimal accumulatedValue = _values.Sum();
				newPoint = new DatedSeriePoint(point.X, accumulatedValue / _period);
			}

			return newPoint;
		}

		public override void Clear()
		{
			_values.Clear();
			_valuesProcessed = 0;
			base.Clear();
		}

		#endregion
	}
}
